<template>
  <div class="app-container" :size="size">
    <el-form :model="queryParams" ref="queryForm" :size="size" :inline="true" v-show="showSearch" label-width="68px" >
      <el-form-item label="属性编码" prop="attrCode">
        <el-input
          v-model="queryParams.attrCode"
          placeholder="请输入属性编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性名称" prop="attrName">
        <el-input
          v-model="queryParams.attrName"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="请选择属性状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
	      <el-button icon="el-icon-search" class="query-btn" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" class="reset-btn" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          class="add-btn"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['goods:attr:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          class="expand-btn"
          plain
          icon="el-icon-sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      border stripe
      v-if="refreshTable"
      v-loading="loading"
      :data="attrList"
      row-key="attrId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="属性名称" header-align="center" prop="attrName" :show-overflow-tooltip="true" />
      <el-table-column label="属性编码" align="center" prop="attrCode" :show-overflow-tooltip="true" />
      <el-table-column label="属性值类型" align="center" prop="valueType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_attr_type" :value="scope.row.valueType"/>
        </template>
      </el-table-column>
      <el-table-column label="属性值单位" align="center" prop="valueUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_attr_unit" :value="scope.row.valueUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="是否多选" align="center" prop="valueRadio">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.valueRadio"/>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="updateBy" />
      <el-table-column label="操作时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="状态" align="center" prop="delFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="'m' === scope.row.attrType"
            class="add-btn"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['goods:attr:edit']"
          >新增</el-button>
          <el-button
            class="edit-btn"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:attr:edit']"
          >修改</el-button>
          <el-button
            class="del-btn"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:attr:remove']"
          >删除</el-button>
          <el-button
            v-if="'m' !== scope.row.attrType"
            class="show-btn"
            type="text"
            icon="el-icon-d-arrow-right"
            @click="handleAttrVal(scope.row)"
            v-hasPermi="['goods:attr:query']"
          >属性值</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="属性菜单" prop="parentId">
              <treeselect v-model="form.parentId" :show-count="true" :options="options.attrOptions" :normalizer="normalizer" placeholder="请选择属性菜单" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性类型" prop="attrType">
              <el-select v-model="form.attrType" placeholder="请选择属性类型" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sys_goods_attr_menu"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="属性编码" prop="attrCode">
              <el-input v-model="form.attrCode" placeholder="请输入属性编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性名称" prop="attrName">
              <el-input v-model="form.attrName" placeholder="请输入属性名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="属性值类型" prop="valueType">
              <el-select v-model="form.valueType" placeholder="请选择属性值类型" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sys_goods_attr_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性值单位" prop="valueUnit">
              <!-- <el-input v-model="form.valueUnit" placeholder="请输入属性值单位" /> -->
              <el-select v-model="form.valueUnit" placeholder="请输入属性值单位" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sys_goods_attr_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- <el-form-item label="是否多选" prop="valueRadio">
              <el-select v-model="form.valueRadio" placeholder="请选择属性值是否多选" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="是否多选" prop="valueRadio">
              <el-radio-group v-model="form.valueRadio">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="delFlag">
              <el-radio-group v-model="form.delFlag">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">商品属性值列表</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button class="add-btn" icon="el-icon-plus" @click="handleAddSprdGoodsAttrVal">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button class="del-btn" icon="el-icon-delete" @click="handleDeleteSprdGoodsAttrVal">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="sprdGoodsAttrValList" :row-class-name="rowSprdGoodsAttrValIndex" @selection-change="handleSprdGoodsAttrValSelectionChange" ref="sprdGoodsAttrVal">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="属性值键值" prop="valueKey" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueKey" placeholder="请输入属性值键值" />
            </template>
          </el-table-column>
          <el-table-column label="属性值显示" prop="valueLabel" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueLabel" placeholder="请输入属性值显示" />
            </template>
          </el-table-column>
          <el-table-column label="显示顺序" prop="orderNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.orderNum" placeholder="请输入显示顺序" />
            </template>
          </el-table-column>
          <el-table-column label="是否默认" prop="isDefault" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isDefault" placeholder="请选择是否默认">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="delFlag" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.delFlag" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="save-btn" @click="submitForm">确 定</el-button>
        <el-button class="cancel-btn" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttr, getAttr, delAttr, addAttr, updateAttr, optionMenuselect } from "@/api/goods/attr";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Attr",
  dicts: ['sys_yes_no', 'sys_normal_disable', 'sys_goods_attr_type', 'sys_goods_attr_unit', 'sys_goods_attr_menu'],
  components: {
    Treeselect
  },
  computed: {
    size() {
      return this.$store.getters.size
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 子表选中数据
      checkedSprdGoodsAttrVal: [],
      // 显示搜索条件
      showSearch: true,
      // 商品属性表格数据
      attrList: [],
      // 商品属性值表格数据
      sprdGoodsAttrValList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        attrCode: null,
        attrName: null,
        delFlag: '0',
      },
      // 下拉框、树数据
      options: {
        // 商品属性树选项
        attrOptions: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        attrCode: [
          { required: true, message: "属性编码不能为空", trigger: "blur" }
        ],
        attrName: [
          { required: true, message: "属性名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getTreeselect();
    this.getList();
  },
  methods: {
    /** 查询商品属性列表 */
    getList() {
      this.loading = true;
      listAttr(this.queryParams).then(response => {
        this.attrList = this.handleTree(response.data, "attrId", "parentId");
        this.loading = false;
      });
    },
    /** 转换商品属性数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.attrId,
        label: node.attrName,
        children: node.children
      };
    },
	  /** 查询商品属性下拉树结构 */
    getTreeselect() {
      optionMenuselect().then(response => {
        this.options.attrOptions = [];
        const data = { attrId: 0, attrName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "attrId", "parentId");
        this.options.attrOptions.push(data);
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attrId: null,
        parentId: 0,
        attrType: 'a',
        attrCode: null,
        attrName: null,
        valueType: null,
        valueUnit: null,
        valueRadio: null,
        delFlag: '0',
        remark: null
      };
      this.sprdGoodsAttrValList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row && row.attrId) {
        this.form.parentId = row.attrId;
      }
      this.open = true;
      this.title = "添加商品属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attrId = row.attrId
      getAttr(attrId).then(response => {
        this.form = response.data;
        this.sprdGoodsAttrValList = response.data.sprdGoodsAttrValList;
        this.open = true;
        this.title = "修改商品属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sprdGoodsAttrValList = this.sprdGoodsAttrValList;
          if (this.form.attrId != null) {
            updateAttr(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttr(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attrId = row.attrId;
      this.$modal.confirm('是否确认删除商品属性名称为 "' + row.attrName + '" 的数据项？').then(function() {
        return delAttr(attrId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 商品属性值序号 */
    rowSprdGoodsAttrValIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 商品属性值添加按钮操作 */
    handleAddSprdGoodsAttrVal() {
      let obj = {};
      let orderNum = !!this.sprdGoodsAttrValList ? this.sprdGoodsAttrValList.length+1 : 1
      obj.valueKey = "";
      obj.valueLabel = "";
      obj.orderNum = orderNum;
      obj.isDefault = "N";
      obj.delFlag = "0";
      obj.remark = "";
      this.sprdGoodsAttrValList.push(obj);
    },
    /** 商品属性值删除按钮操作 */
    handleDeleteSprdGoodsAttrVal() {
      if (this.checkedSprdGoodsAttrVal.length == 0) {
        this.$modal.msgError("请先选择要删除的商品属性值数据");
      } else {
        const sprdGoodsAttrValList = this.sprdGoodsAttrValList;
        const checkedSprdGoodsAttrVal = this.checkedSprdGoodsAttrVal;
        this.sprdGoodsAttrValList = sprdGoodsAttrValList.filter(function(item) {
          return checkedSprdGoodsAttrVal.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSprdGoodsAttrValSelectionChange(selection) {
      this.checkedSprdGoodsAttrVal = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/attr/export', {
        ...this.queryParams
      }, `attr_${new Date().getTime()}.xlsx`)
    },
    /** 属性值详情 */
    handleAttrVal: function(row) {
      const attrId = row.attrId;
      this.$router.push("/goods/attr-val/index/" + attrId);
    },
  }
};
</script>
